package com.dao;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

import com.base.BaseDao;
import com.bean.TfAccountRecord;
import com.tool.DateTimeTools;
import com.util.GUtil;

/**
 	* A data access object (DAO) providing persistence and search support for TfAccountRecord entities.
 			* Transaction control of the save(), update() and delete() operations 
		can directly support Spring container-managed transactions or they can be augmented	to handle user-managed Spring transactions. 
		Each of these methods provides additional information for how to configure it for the desired type of transaction control. 	
	 * @see com.bean.TfAccountRecord
  * @author MyEclipse Persistence Tools 
 */
public class TfAccountRecordDao extends BaseDao  {
	     private static final Logger log = Logger.getLogger(TfAccountRecordDao.class);
		//property constants
	public static final String AMOUNT = "amount";
	public static final String TYPE = "type";
	public static final String STATUS = "status";


	public String queryByDay(List<TfAccountRecord> payInOut, List<TfAccountRecord> payStat, String daytime)throws Exception {
		return this.queryByTime(payInOut, payStat, daytime);
	}
	public String queryByTime(List<TfAccountRecord> payInOut, List<TfAccountRecord> payStat, String daytime)throws Exception {

		if(payInOut==null || payStat==null || daytime==null)
			return "传入参数均不能为空"; //GUtil.FAILE;
	
		session = this.getSession();
		String hql = "select new com.bean.TfAccountRecord(sum(amount), type) from TfAccountRecord" +
				" where createTime like '"+daytime+"%'" +
				" GROUP BY type";
		Query query = session.createQuery(hql);
		List<TfAccountRecord> p1 = query.list();
		payInOut.addAll(p1);

		hql = "select new com.bean.TfAccountRecord(sum(amount),type,category) from TfAccountRecord" +
				" where createTime like '"+daytime+"%'" +
				" GROUP BY category";
		query = session.createQuery(hql);
		List<TfAccountRecord> p2 = query.list();
		payStat.addAll(p2);
		return GUtil.SUCCESS;
	}
	public Double [][] queryByWeek(List<TfAccountRecord> payInOut,
			List<TfAccountRecord> payStat,
			Map<Double, Double> paylistInOutByDay, String weektime)
					throws Exception {

		SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
		//String weektime = "2014-05-06";
		Date timelong = formatDate.parse(weektime);
		Timestamp inTime = new Timestamp(timelong.getTime());
		Timestamp outStartTime = new Timestamp(timelong.getTime());
		Timestamp outEndTime = new Timestamp(timelong.getTime());
		DateTimeTools.getWeekDays(inTime, outStartTime, outEndTime);//获取月的开始和结束时间，从而获取本月的最后一天，即获取本月的长度

		//查询 payInOut、payStat
		session = this.getSession();
		String hql = "select new com.bean.TfAccountRecord(sum(amount), type) from TfAccountRecord" +
				" where createTime between ? and ? " +
				" GROUP BY type";
		Query query = session.createQuery(hql);
		query.setTimestamp(0, outStartTime);
		query.setTimestamp(1, outEndTime);
		List<TfAccountRecord> p1 = query.list();
		payInOut.addAll(p1);

		hql = "select new com.bean.TfAccountRecord(sum(amount),type,category) from TfAccountRecord" +
				" where createTime between ? and ? " +
				" GROUP BY category";
		query = session.createQuery(hql);
		query.setTimestamp(0, outStartTime);
		query.setTimestamp(1, outEndTime);
		List<TfAccountRecord> p2 = query.list();
		payStat.addAll(p2);

		//统计7天数据
		//query paylistInOutByDay

		int enddate = 7;// outEndTime.getDate();
		Double[][] data = new Double[3][enddate];
		for(int i=0; i<3; i++){
			for(int j=0; j<enddate; j++){
				if(i==0)
					data[i][j] = (double)(j+1);
				else
					data[i][j] = 0.0;
			}
		}

		hql = "SELECT new com.bean.TfAccountRecord( year(createTime),month(createTime),day(createTime),sum(amount),type ) " +
				"from TfAccountRecord "+
				"where createTime between ? and ?  "+
				"GROUP BY day(createTime),type ";
		query = session.createQuery(hql);
		query.setTimestamp(0, outStartTime);
		query.setTimestamp(1, outEndTime);
		List<TfAccountRecord> list = query.list();
		if(list!=null){
			for(TfAccountRecord par : list){
				if(par!=null)
					if(par.getDay()>outStartTime.getDate())
						data[par.getType()][par.getDay() - outStartTime.getDate()] = Math.abs(par.getAmount());
			}
		}else{
			return null;
		}
		log.info( this.getClass()+".queryByWeek() "+data.toString());
		return data;
		
	}
	public Double [][] queryByMonth(List<TfAccountRecord> payInOut,
			List<TfAccountRecord> payStat,
			Map<Double, Double> paylistInOutByDay, String monthtime)
					throws Exception {
		
		String ret = this.queryByTime(payInOut, payStat, monthtime);//查询 payInOut、payStat
		
		if( ret.equals(GUtil.SUCCESS) ){

			SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM");
			//String datetime = "2014-05";
			Date timelong = formatDate.parse(monthtime);
			Timestamp inTime = new Timestamp(timelong.getTime());
			Timestamp outStartTime = new Timestamp(timelong.getTime());
			Timestamp outEndTime = new Timestamp(timelong.getTime());
			DateTimeTools.getMonthDays(inTime, outStartTime, outEndTime);//获取月的开始和结束时间，从而获取本月的最后一天，即获取本月的长度

			int enddate = outEndTime.getDate();
			Double[][] data = new Double[3][enddate];
			for(int i=0; i<3; i++){
				for(int j=0; j<enddate; j++){
					if(i==0)
						data[i][j] = (double)(j+1);
					else
						data[i][j] = 0.0;
				}
			}

			session = this.getSession();
			String hql = "SELECT new com.bean.TfAccountRecord( year(createTime),MONTH(createTime),day(createTime),sum(amount),type) " +
					"from TfAccountRecord "+
					"where createTime like '"+monthtime+"%'"+
					"GROUP BY year(createTime),MONTH(createTime),day(createTime),type ";
			Query query = session.createQuery(hql);
			List<TfAccountRecord> list = query.list();
			if(list!=null){
				for(TfAccountRecord par : list){
					if(par!=null)
						data[par.getType()][par.getDay()-1] = Math.abs(par.getAmount());
				}
			}else{
				return null;
			}
			log.info( data.toString());
			return data;
		}
		return null;
	}
	public Double [][] queryByYear(List<TfAccountRecord> payInOut,
			List<TfAccountRecord> payStat,
			Map<Double, Double> paylistInOutByDay, String yeartime)
					throws Exception {

		String ret = this.queryByTime(payInOut, payStat, yeartime);//查询 payInOut、payStat
		if( ret.equals(GUtil.SUCCESS) ){

			int enddate = 12;// outEndTime.getDate();
			Double[][] data = new Double[3][enddate];
			for(int i=0; i<3; i++){
				for(int j=0; j<enddate; j++){
					if(i==0)
						data[i][j] = (double)(j+1);
					else
						data[i][j] = 0.0;
				}
			}

			session = this.getSession();
			String hql = "SELECT new com.bean.TfAccountRecord( year(createTime),month(createTime),sum(amount),type) " +
					"from TfAccountRecord "+
					"where createTime like '"+yeartime+"%'"+
					"GROUP BY year(createTime),month(createTime),type ";
			Query query = session.createQuery(hql);
			List<TfAccountRecord> list = query.list();
			if(list!=null){
				for(TfAccountRecord par : list){
					if(par!=null)
						data[par.getType()][par.getMonth()-1] = Math.abs(par.getAmount());
				}
			}else{
				return null;
			}
			log.info(this.getClass()+".queryByYear()"+ data.toString());
			return data;
		}
		return null;
	}
    public void save(TfAccountRecord transientInstance) {
        log.debug("saving TfAccountRecord instance");
        try {
            getSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
	public void delete(TfAccountRecord persistentInstance) {
        log.debug("deleting TfAccountRecord instance");
        try {
            getSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    public TfAccountRecord findById( java.lang.Long id) {
        log.debug("getting TfAccountRecord instance with id: " + id);
        try {
            TfAccountRecord instance = (TfAccountRecord) getSession()
                    .get("com.dao.TfAccountRecord", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    
    public List findByExample(TfAccountRecord instance) {
        log.debug("finding TfAccountRecord instance by example");
        try {
            List results = getSession()
                    .createCriteria("com.dao.TfAccountRecord")
                    .add(Example.create(instance))
            .list();
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
    public List findByProperty(String propertyName, Object value) {
      log.debug("finding TfAccountRecord instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from TfAccountRecord as model where model." 
         						+ propertyName + "= ?";
         Query queryObject = getSession().createQuery(queryString);
		 queryObject.setParameter(0, value);
		 return queryObject.list();
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	public List findByAmount(Object amount
	) {
		return findByProperty(AMOUNT, amount
		);
	}
	
	public List findByType(Object type
	) {
		return findByProperty(TYPE, type
		);
	}
	
	public List findByStatus(Object status
	) {
		return findByProperty(STATUS, status
		);
	}
	

	public List findAll() {
		log.debug("finding all TfAccountRecord instances");
		try {
			String queryString = "from TfAccountRecord";
	         Query queryObject = getSession().createQuery(queryString);
			 return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
    public TfAccountRecord merge(TfAccountRecord detachedInstance) {
        log.debug("merging TfAccountRecord instance");
        try {
            TfAccountRecord result = (TfAccountRecord) getSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(TfAccountRecord instance) {
        log.debug("attaching dirty TfAccountRecord instance");
        try {
            getSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(TfAccountRecord instance) {
        log.debug("attaching clean TfAccountRecord instance");
        try {
            getSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
}